package net.ossrs.yasea;

import android.graphics.Bitmap;
import android.os.Environment;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;


//图片文件，与 byte[] 互转
public class TestFile {

    static byte[] bytes;

    public static void bytesToImageFile(byte[] bytes) {
        try {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaa.bin");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes, 0, bytes.length);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void bSave(byte[] bgraData1, int width, int height) {
        byte[] bgraData = new byte[width * height * 4];
        rgba_to_bgra(bgraData1, bgraData, width*height);
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        ByteBuffer buf = ByteBuffer.wrap(bgraData);
        bitmap.copyPixelsFromBuffer(buf);
        String strFileName = "a.jpg";

        File file = new File(Environment.getExternalStorageDirectory(), strFileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void rgba_to_bgra(byte[] src, byte[] dst, int numPixels) {
        int col;
        for (col = 0; col < numPixels; col++) {
            dst[0 + col * 4] = src[2 + col * 4];
            dst[1 + col * 4] = src[1 + col * 4];
            dst[2 + col * 4] = src[0 + col * 4];
            dst[3 + col * 4] = src[3 + col * 4];
        }
    }
}